package com.cssl.service.impl;


import com.cssl.domain.DtsSearchHistory;

import com.cssl.domain.dto.DtsSearchHistoryDto;

import com.cssl.service.DtsSearchHistoryService;
import com.cssl.mapper.DtsSearchHistoryMapper;
import com.cssl.util.RedisUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 黄鑫
 * @description 针对表【dts_search_history(搜索历史表)】的数据库操作Service实现
 * @createDate 2024-08-03 09:20:40
 */
@Service
public class DtsSearchHistoryServiceImpl
        implements DtsSearchHistoryService {
    @Autowired
    private DtsSearchHistoryMapper historyMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Map getHistoryList(DtsSearchHistoryDto historyDto) {
        // Redis Key 存储，包含页码和条件
        StringBuilder redisKeyBuilder = new StringBuilder("HistoryList");


        if (historyDto.getUserId() != null && historyDto.getUserId() != 0) {
            redisKeyBuilder.append(":UserId:").append(historyDto.getUserId());
        }

        // 检查手机号
        if (historyDto.getKeyword() != null && historyDto.getKeyword().isEmpty()) {
            redisKeyBuilder.append(":Keyword:").append(historyDto.getKeyword());
        }

        redisKeyBuilder.append(":page:").append(historyDto.getPageNum());
        String redisKey = redisKeyBuilder.toString();

        List<DtsSearchHistory> histories = null;

        // 检查 Redis 中是否存在当前页的数据
        if (redisUtil.hasKey(redisKey)) {
            System.out.println("从 Redis 中获取数据");
            histories = (List<DtsSearchHistory>) redisUtil.get(redisKey);
            Map<String, Object> map1 = new HashMap<>();
            // 获取存储的总数

            map1.put("list", histories);
            map1.put("total", redisUtil.get("HistoryList:total")); // 使用从 Redis 获取的总数
            map1.put("pageNum", historyDto.getPageNum());
            map1.put("pageSize", historyDto.getPageSize());
            return map1;
        } else {
            // 开始分页
            Page page = PageHelper.startPage(historyDto.getPageNum(), historyDto.getPageSize());
            System.out.println("从数据库中查询数据");
            histories = historyMapper.getHistoryList(historyDto);
            Map<String, Object> map = new HashMap<>();
            // 计算总数
//            long total = page.getTotal();

            // 将查询结果放入 Redis，设置过期时间，例如：1小时
            redisUtil.set(redisKey, histories, 3600);
            redisUtil.set("HistoryList:total", historyMapper.getDtsHistoryCount(), 3600);

            map.put("list", page.getResult());
            map.put("total", page.getTotal()); // 使用从数据库计算的总数
            map.put("totalPage", page.getPages());
            map.put("pageNum", page.getPageNum());
            map.put("pageSize", page.getPageSize());
            return map;
        }
    }
}




